use std::io::{self, Read, Write};
use std::os::unix::net::UnixStream;

const SOCKET_NAME: &str = "/tmp/DemoSocket";
const BUFFER_SIZE: usize = 128;

fn main() -> io::Result<()> {
    let mut data_socket = UnixStream::connect(SOCKET_NAME)?;

    loop {
        println!("Enter number to send to server:");
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        let i: i32 = input.trim().parse().expect("Invalid input");

        let sent_bytes = data_socket.write(&i.to_ne_bytes())?;
        println!("No of bytes sent = {}, data sent = {}", sent_bytes, i);

        if i == 0 {
            break;
        }
    }

    // Request result.
    let mut buffer = [0; BUFFER_SIZE];
    let res_str = "RES\0";
    data_socket.write_all(res_str.as_bytes())?;

    // Receive result.
    let bytes_read = data_socket.read(&mut buffer)?;
    let result = String::from_utf8_lossy(&buffer[..bytes_read]);

    // Print result.
    println!("Result = {}", result);

    Ok(())
}
